# -*- coding: utf-8 -*-
import random
import subprocess
import time
import logging
import argparse

from appium import webdriver
# from appium.options.android import UiAutomator2Options
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
logger = logging

APP = "XHS"

app_package_map = {
    "XHS": ("com.xingin.xhs", ".index.v2.IndexActivityV2")
}


class XHSAppiumOperate:
    def __init__(self, **kwargs):
        self.screen_width = None
        self.screen_height = None

        self.deviceName = kwargs.get("deviceName")
        self.appium_url = kwargs.get("appium_url")
        self.platformVersion = kwargs.get("platformVersion")
        self.systemPort = kwargs.get("systemPort")
        self.adbPort = kwargs.get("adbPort")
        self.user_name = kwargs.get("text")
        self.introduce = kwargs.get("introduce")
        self.job_id = kwargs.get("job_id")
        self.driver = None
        self.max_retries = 3
        self.failure_count = 0

    def run(self):
        while self.max_retries > 0:
            try:
                if self.driver:
                    self.driver.quit()
                self.connection()
                logger.info(f"设备 {self.deviceName} 连接成功")
                time.sleep(3)

                logger.info("开始执行小红书【设置作品权限为仅自己可见】任务...")
                self.script()
                break
            except Exception as e:
                logger.error(f"发生异常: {e}")
                self.failure_count += 1
                self.max_retries -= 1
                if self.max_retries == 0:
                    raise
        logger.info("任务结束")

    @staticmethod
    def execute_adb_command(adb_command):
        """
        执行单条 ADB 命令

        :param adb_command: 完整的 ADB 命令字符串
        :return: 命令执行结果（stdout）
        """
        try:
            logger.info(f"执行 ADB 命令: {adb_command}")
            result = subprocess.run(
                adb_command,
                shell=True,
                check=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
            logger.info(f"命令执行成功: {adb_command}")
            return result.stdout.decode('utf-8')
        except subprocess.CalledProcessError as e:
            logger.error(f"命令执行失败: {adb_command}")
            logger.error(f"错误信息: {e.stderr.decode('utf-8')}")

    def initialize_device_settings(self):
        """
        执行设备初始化所需的 ADB 命令
        """
        logger.info("开始初始化设备设置")

        commands = [
            f"adb -s {self.deviceName} -P {self.adbPort} shell settings put global adb_keep_usb_enabled 1",
            f"adb -s {self.deviceName} -P {self.adbPort} shell settings put global miui_optimization 0",
            f"adb -s {self.deviceName} -P {self.adbPort} shell settings put global tcp_keepalive 1",
            f"adb -s {self.deviceName} -P {self.adbPort} shell dumpsys battery unplug",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm enable io.appium.uiautomator2.server",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm enable io.appium.uiautomator2.server.test",
            f"adb -s {self.deviceName} -P {self.adbPort} shell settings put global background_process_limit 5",
            f"adb -s {self.deviceName} -P {self.adbPort} shell am set-standby-bucket io.appium.uiautomator2.server ACTIVE",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm trim-caches 500M",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm clear io.appium.uiautomator2.server",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm clear io.appium.uiautomator2.server.test"
        ]

        for cmd in commands:
            try:
                self.execute_adb_command(cmd)
            except Exception as e:
                logger.error(f"执行命令失败: {cmd}")
                logger.error(f"错误详情: {e}")

    def connection(self):
        self.initialize_device_settings()
        desired_caps = {
            "platformName": "Android",
            # "udid": "FMR0223A31045650",
            "udid": self.deviceName,
            "platformVersion": self.platformVersion,
            "deviceName": self.deviceName,
            "automationName": "UiAutomator2",
            "appPackage": app_package_map[APP][0],
            "appActivity": app_package_map[APP][1],
            "noReset": True,
            "fullReset": False,
            "systemPort": int(self.systemPort),
            "adbPort": int(self.adbPort),
            "appWaitForLaunch": True,
            "noSign": True,
            "autoLaunch": True,
            "newCommandTimeout": 180,
            "skipLogcatCapture": True,
            "disableWindowAnimation": True,
            "disableAndroidWatchers": True,
            "adbExecTimeout": 30000,
            "uiautomator2ServerInstallTimeout": 60000,
            "skipDeviceInitialization": True,
        }

        # self.driver = webdriver.Remote(self.appium_url, options=UiAutomator2Options().load_capabilities(desired_caps))
        self.driver = webdriver.Remote(self.appium_url, desired_caps)
        self.screen_width, self.screen_height = self.get_window_size()
        self.wait_time = 2

    def script(self):
        logger.info("开始执行【账号装修】任务")
        logger.info("点击我的页面")
        self.find_element_with_retry(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().description("我")').click()
        time.sleep(5)

        logger.info("点击编辑资料")

        self.find_element_with_retry(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("编辑资料")').click()
        time.sleep(5)
        logger.info("修改头像")
        self.find_element_with_retry(AppiumBy.ANDROID_UIAUTOMATOR,
                                     'new UiSelector().className("android.widget.ImageView").instance(2)').click()
        time.sleep(5)

        logger.info("上传新头像")
        self.find_element_with_retry(AppiumBy.ANDROID_UIAUTOMATOR,
                                     'new UiSelector().text("上传新头像")').click()
        time.sleep(5)
        logger.info("选择图片")
        self.find_element_with_retry(AppiumBy.ANDROID_UIAUTOMATOR,
                                     'new UiSelector().className("android.widget.RelativeLayout").instance(2)').click()
        time.sleep(5)
        save_button = self.find_element_with_retry(
            AppiumBy.ANDROID_UIAUTOMATOR,
            'new UiSelector().text("保存")'
        )
        if save_button:
            save_button.click()

        done_button = self.find_element_with_retry(
            AppiumBy.ANDROID_UIAUTOMATOR,
            'new UiSelector().text("完成")'
        )
        if done_button:
            done_button.click()
        logger.info("保存成功")
        time.sleep(20)
        self.driver.press_keycode(3)

        logger.info("修改姓名")

        self.find_element_with_retry(AppiumBy.ANDROID_UIAUTOMATOR,
                                     'new UiSelector().text("名字")').click()

        text_input = self.find_element_with_retry(AppiumBy.ANDROID_UIAUTOMATOR,
                                                  'new UiSelector().resourceId("text-input")')
        text_input.send_keys(self.user_name)

        time.sleep(5)

        self.find_element_with_retry(AppiumBy.ANDROID_UIAUTOMATOR,
                                     'new UiSelector().text("保存")"]').click()

        self.driver.press_keycode(3)

        logger.info("修改简介")

        self.find_element_with_retry(AppiumBy.ANDROID_UIAUTOMATOR,
                                     'new UiSelector().text("简介")').click()
        time.sleep(5)

        introduce_text_input = self.find_element_with_retry(AppiumBy.XPATH,
                                                            '//android.widget.EditText[@resource-id="com.xingin.xhs:id/0_resource_name_obfuscated"]')

        introduce_text_input.send_keys(self.introduce)

        time.sleep(5)

        # self.find_element_with_retry(AppiumBy.ANDROID_UIAUTOMATOR,
        #                              'new UiSelector().text("保存")"]').click()
        #
        # self.driver.press_keycode(3)

        logger.info("所有作品权限设置完成,不关闭窗口,麻烦人工确认")
        # self.normal_end()

    def swipe_to_next(self):
        # 向上滑动
        self.driver.swipe(
            self.screen_width / 2,
            self.screen_height * 0.8,
            self.screen_width / 2,
            self.screen_height * 0.2,
            200
        )

    def find_element_with_retry(self, by, value, timeout=5):
        max_retries = 3
        for attempt in range(max_retries + 1):
            try:
                element = WebDriverWait(self.driver, timeout).until(
                    EC.presence_of_element_located((by, value))
                )
                return element
            except Exception as e:
                if attempt < max_retries:
                    logger.error(f"获取元素失败，重试")
                    time.sleep(1)  # 等待1秒后重试
                else:
                    logger.error(f"获取元素失败，超过3次")
                    return None

    def get_window_size(self):
        size = self.driver.get_window_size()
        return size['width'], size['height']

    def normal_end(self):
        logger.info("返回首页并退出")
        self.driver.press_keycode(3)  # HOME 键
        self.driver.quit()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-j', '--job_id', dest='job_id', type=str, default=None, required=True, help='target job_id')
    parser.add_argument('-u', '--appium_url', dest='appium_url', type=str, default=None, help='target appium_url')
    parser.add_argument('-d', '--deviceName', dest='deviceName', type=str, default=None, help='target deviceName')
    parser.add_argument('-s', '--systemPort', dest='systemPort', type=str, default=None, help='target systemPort')
    parser.add_argument('-a', '--adbPort', dest='adbPort', type=str, default=None, help='target adbPort')
    parser.add_argument('-p', '--platformName', dest='platformName', type=str, default=None, help='target platformName')
    parser.add_argument('-ver', '--platformVersion', dest='platformVersion', type=str, default=None,
                        help='target platformVersion')
    parser.add_argument('-accountId', '--accountId', dest='accountId', type=str, default="000", help='target accountId')
    parser.add_argument('-v', '--variables', dest='variables', type=str, default='{}', help='target variables')
    parser.add_argument('-text', '--text', dest='text', type=str, default='',
                        help='姓名')
    parser.add_argument('-introduce', '--introduce', dest='introduce', type=str, default='',
                        help='简介')
    parser.add_argument('-file', '--file', type=str, required=False)

    args = parser.parse_args()
    XHSAppiumOperate(**vars(args)).run()
